/*
 * @Author: zqx me_zqx@163.com
 * @Date: 2025-01-02 10:53:54
 * @LastEditors: zqx me_zqx@163.com
 * @LastEditTime: 2025-09-17 15:54:49
 * @FilePath: /XMate-h5/src/router/index.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { createRouter, createWebHashHistory } from "vue-router";
import routes from "./routes";
import NProgress from "@/utils/progress";
import setPageTitle from "@/utils/set-page-title";
import { isPC } from "@/utils/platformTool";
import { openInNewTab as openInNewTabUrlTool } from "@/utils/urlTool";

const router = createRouter({
  history: createWebHashHistory(),
  routes
});

router.beforeEach((to, from, next) => {
  console.log("beforeEach to: ", to);
  console.log("beforeEach from: ", from);
  let TempOpenInNewTab = (isPC() ? to.meta.openInNewTabPC : to.meta.openInNewTab) || false;
  if (from.meta.disableOpenInNewTab ) {
    TempOpenInNewTab = false;
  }
  if ( TempOpenInNewTab && from.name) {
    openInNewTab(to, next);
    return;
  }

  NProgress.start();
  const { xm } = to.query;
  if (xm) {
    sessionStorage.setItem("xm", true);
  }
  // 页面 title
  setPageTitle(to.meta.title);
  setCommonBotTitle(to);
  next();
});

router.afterEach(() => {
  NProgress.done();
});

const setCommonBotTitle = to => {
  if (to.fullPath.includes("/commonCozeBot")) {
    const { query } = to;
    const { botId } = query;
    if (botId) {
      if (botId === "7381282707588399141") setPageTitle("讲师信息查询宝");
      if (botId === "7366888150595731494") setPageTitle("报价小助理");
    }
  }
};

const openInNewTab = (to, next) => {
  let url = router.resolve(to).href;
  const { hiddenAppBar = false } = to.meta;
  try {
    const { origin, pathname } = window.location;
    let host = origin + pathname;
    url = host + url;
    console.log("openInNewTab url", url);
    openInNewTabUrlTool(url, hiddenAppBar);
    next(false);
  } catch (error) {
    next(true);
    console.log("openInNewTab url 2", url);
  }
};


export default router;
